package com.mrd.gtimp.business.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.abc.trustpay.client.ebus.PaymentResult;
import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.exception.DeleteException;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.BusinessDto;
import com.mrd.gtimp.business.entity.BaseBusiness;
import com.mrd.gtimp.business.entity.Booking;
import com.mrd.gtimp.business.entity.CancelReason;
import com.mrd.gtimp.business.entity.CarMsg;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Contacter;
import com.mrd.gtimp.business.entity.Container;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.DeclarationFree;
import com.mrd.gtimp.business.entity.DeclarationModel;
import com.mrd.gtimp.business.entity.GoodAddress;
import com.mrd.gtimp.business.entity.GoodAddressModel;
import com.mrd.gtimp.business.entity.Goods;
import com.mrd.gtimp.business.entity.PackingListDetailed;
import com.mrd.gtimp.business.entity.RejectContent;
import com.mrd.gtimp.business.entity.SuiFuDan;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.gtimp.business.entity.TrailModel;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.mrd.gtimp.business.service.BookingBiz;
import com.mrd.gtimp.business.service.BusinessBiz;
import com.mrd.gtimp.business.service.CancelReasonBiz;
import com.mrd.gtimp.business.service.CarMsgBiz;
import com.mrd.gtimp.business.service.CompanyQpBiz;
import com.mrd.gtimp.business.service.ContacterBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.DeclarationFreeBiz;
import com.mrd.gtimp.business.service.DeclarationModelBiz;
import com.mrd.gtimp.business.service.FundFlowBiz;
import com.mrd.gtimp.business.service.GoodAddressBiz;
import com.mrd.gtimp.business.service.PackingListDetailedBiz;
import com.mrd.gtimp.business.service.PaymentABCBiz;
import com.mrd.gtimp.business.service.PaymentPlatformBiz;
import com.mrd.gtimp.business.service.RejectContentBiz;
import com.mrd.gtimp.business.service.SuiFuDanBiz;
import com.mrd.gtimp.business.service.TrailBiz;
import com.mrd.gtimp.business.service.TrailModelBiz;
import com.mrd.gtimp.order.action.OrderAction;
import com.mrd.gtimp.v2.fund.FundIETypeEnum;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.LoginUtil;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class BusinessAction {

  private final org.slf4j.Logger logger = LoggerFactory.getLogger(BusinessAction.class);

  private static final long serialVersionUID = 1L;

  @Resource
  private PackingListDetailedBiz packingListDetailedBiz;

  @Resource
  private BusinessBiz businessBiz;

  @Resource
  private CompanyBiz companyBiz;

  @Resource
  private GoodAddressBiz goodAddressBiz;

  @Resource
  private BookingBiz bookBiz;

  @Resource
  private TrailBiz trailBiz;

  @Resource
  private TrailModelBiz trailModelBiz;

  @Resource
  private DeclarationBiz declaBiz;

  @Resource
  private DeclarationModelBiz declaModelBiz;

  @Resource
  private ContacterBiz contacterBiz;

  @Resource
  private UserBiz userBiz;

  @Resource
  private AttachmentBiz attachmentBiz;

  @Resource
  private CancelReasonBiz cancelReasonBiz;

  @Resource
  private RejectContentBiz rejectContentBiz;

  @Resource
  private PaymentABCBiz paymentABCBiz;

  @Resource
  private DeclarationFreeBiz declarationFreeBiz;

  @Resource
  private BookingAction bAction;
  @Resource
  private TrailAction tAction;
  @Resource
  private DeclarationAction dAction;

  @Resource
  private CarMsgBiz carMsgBiz;

  @Resource
  private CompanyQpBiz companyQpBiz;
  @Resource
  private DeclarationBiz declarationBiz;
  @Resource
  private OrderAction orderAction;
  @Resource
  private PaymentPlatformBiz paymentPlatformBiz;
  @Resource
  private JedisClientClusterImpl jedisClientCluster;

  // 业务类型
  private String[][] businessType;

  // 港口
  private String[][] ports;

  // 单位类型
  private String[][] units;

  // 币制类型
  private String[][] currencys;

  // 国家类型
  private String[][] countries;

  // 成交方式
  private String[][] deals;

  // // 业务列表
  // List<BusinessDto> busiDtos;

  // 各业务的状态
  private String state;

  // 拖车毛重
  private String goodGw;

  // 拖车中已经去重的柜列表，在拖车修改的时候进行初始化，方便页面操作
  // private List<Container> containers;

  //
  // /**
  // * 发货人
  // */
  // private Contacter shipper;

  private String bizState;

  /**
   * 修改页面的类型参数
   */
  // private String singleType = "";

  /**
   * 查看详细页面参数（新）
   */
  private String checkDetail = "";

  // /**
  // * 要修改单证的id
  // */
  // private String id = "";

  /**
   * 要修改单证的businessId
   */
  private String businessId = "";

  /**
   * 是否清除业务数据主键的控制符，0不清除，1清除
   */
  private String clearPk = "0";

  /**
   * 是否为模板数据, 1为模板数据
   */
  private String modelType = "";

  /**
   * 报关单是否使用手册
   */
  private String isRecord = "";

  /**
   * 是否为历史载入数据
   */
  private String loadType = "";
  /**
   * 用于判断是否是业务查询页面传回信息 同时也可以做为其他标识
   */
  private String identification = "";
  /**
   * 用于识别历史载入数据，只因要求只载入审核的数据
   */
  private String loadPage = "";

  /**
   * 是否进行提交操作
   */
  private String isSubmit = "";

  /**
   * 用于导出exl表格
   */
  private InputStream ExlStream;
  /**
   * 设置导出exl文件的文件名
   */
  private String exlFileName;

  /**
   * 报关订单费用
   */
  private DeclarationFree declarationFree;

  /**
   * 公司类型
   */
  private String com_type = "";

  /**
   * 若要导入exl 必须从客户端上传exl的文件 以下三个属性石是上传文件的必要属性
   */
  private File importExlFile;
  private String importExlFileName;
  private String importExlContentType;
  private String declareStr;
  /**
   * 获取系统的session 用于获取存在系统中的全局变量
   */
  // private final Map<String, Object> sessionMap = ActionContext.getContext()
  // .getSession();

  // private String pay_id;
  private String payFree;
  private String payMent;
  private String MSG;
  private PaymentResult paymentResult;
  private List<String> declaration_ids;
  // private String paymentType;
  private List<DeclarationFree> declarationFrees;

  /**
   * 农行支付功能常量
   */
  public static String URL_FOR_CUSTOMER_SURE; // 用户确定订单URL

  /**
   * 方法requestForPayment返回值的key定义
   */
  public static final String KEY_paymentURL = "PaymentURL"; // 支付页面URL
  public static final String KEY_request_result = "requestResult"; // 支付请求结果
  public static final String KEY_request_result_success = "SUCCESS"; // 错误信息
  public static final String KEY_request_result_failed = "FAILED"; // 错误信息
  public static final String KEY_errorMessage = "errorMessage"; // 错误信息

  private String sfdTempId;


  @RequestMapping("/business-order")
  public String order() {
    // TODO: 2016/8/17 不在继承需要重新实现
    // businessType = super.setResultByBaseType(BaseTypeConstant.BOOKING_BIZ_TYPE);
    // ports = super.setResultByBaseType(BaseTypeConstant.PORT_TYPE);
    // units = super.setResultByBaseType(BaseTypeConstant.UNIT_TYPE);
    // currencys = super.setResultByBaseType(BaseTypeConstant.CURRENCY_TYPE);
    // countries = super.setResultByBaseType(BaseTypeConstant.COUNTRY_TYPE);
    // deals = super.setResultByBaseType(BaseTypeConstant.DEAL_TYPE);
    return "/gtimp/business/businessStart";
  }

  /**
   * 下拉条--选择供应商
   */
  @RequestMapping("/business-findCompanysByNameType")
  @ResponseBody
  public List<Company> findCompanysByNameType(Jqgrid jqgrid) {
    try {
      // if (filters == null) {
      // filters = new Filter();
      // }
      // filters.setGroupOp(FilterGroupOption.AND);
      List<Company> companys = null;
      Page<Company> companyPage = null;
      String com_type = HttpUtils.getParam("com_type");
      String sup_type = HttpUtils.getParam("sup_type");
      String com_name = HttpUtils.getParam("com_name");
      String com_idefined = HttpUtils.getParam("com_idefined");
      if (com_type.equals(BaseTypeConstant.COMPANY_TYPE_SHIP)) {
        String hql =
            "from com.mrd.gtimp.base.entity.Company t where t.type='SC' and (upper(t.name) like upper(:name) or upper(t.SHORT_NAME) like upper(:name))";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", "%" + com_name + "%");
        List<Object> objects = companyBiz.findObjectByHql(hql, 1, 15, parameters);
        companys = new ArrayList<Company>();
        for (Object object : objects) {
          companys.add((Company) object);
        }
      } else {
        SearchRule sr = new SearchRule("type", SearchRuleOption.eq, com_type);
        jqgrid.addRule(sr);
        if (null != com_name && !"".equals(com_name)) {
          SearchRule sr2 = new SearchRule("name", SearchRuleOption.cn, com_name);
          jqgrid.addRule(sr2);
        }
        if (null != sup_type && !"".equals(sup_type)) {
          SearchRule sr3 = new SearchRule("supTypes.identifier", SearchRuleOption.eq, sup_type);
          jqgrid.addRule(sr3);
        }
        companyPage = companyBiz.findByJqgrid(jqgrid);
      }
      // 订舱时佛山新港没有订舱这个业务
      Company com = null;
      if ("bookingCompany".equals(com_idefined)) {
        for (int i = 0; i < companyPage.getSize(); i++) {
          Company c = companyPage.getContent().get(i);
          if ("佛山新港".equals(c.getName())) {
            com = c;
          }
        }
        if (com != null) {
          companys.remove(com);
        }
      }
      return companys;
    } catch (QueryException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 检测订舱业务代理人下拉内容是否正确
   */
  @RequestMapping("/business-findCompanysByNameTypeIsRight")
  @ResponseBody
  public Page<Company> findCompanysByNameTypeIsRight(Jqgrid jqgrid) {
    try {
      // if (filters == null) {
      // filters = new Filter();
      // }
      // filters.setGroupOp(FilterGroupOption.AND);
      List<Company> companys = null;
      Page<Company> companyPage = null;
      String com_type = HttpUtils.getParam("com_type");
      String sup_type = HttpUtils.getParam("sup_type");
      String com_name = HttpUtils.getParam("com_name");
      if (com_type.equals(BaseTypeConstant.COMPANY_TYPE_SHIP)) {
        String hql =
            "from com.mrd.gtimp.base.entity.Company t where t.type='SC' and (upper(t.name) like upper(:name) or upper(t.SHORT_NAME) like upper(:name))";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", com_name);
        List<Object> objects = companyBiz.findObjectByHql(hql, 1, 15, parameters);
        companys = new ArrayList<Company>();
        for (Object object : objects) {
          companys.add((Company) object);
        }
      } else {
        SearchRule sr = new SearchRule("type", SearchRuleOption.eq, com_type);
        jqgrid.addRule(sr);
        if (null != com_name && !"".equals(com_name)) {
          SearchRule sr2 = new SearchRule("name", SearchRuleOption.eq, com_name);
          jqgrid.addRule(sr2);
        }
        if (null != sup_type && !"".equals(sup_type)) {
          SearchRule sr3 = new SearchRule("supTypes.identifier", SearchRuleOption.eq, sup_type);
          jqgrid.addRule(sr3);
        }
        // companys = companyBiz.findByJqgrid(0, 10, filters, null);
        companyPage = companyBiz.findByJqgrid(jqgrid);
        return companyPage;
      }
    } catch (QueryException e) {
      e.printStackTrace();
    }
    return null;
  }

  @RequestMapping("/business-findFactorysByName")
  @ResponseBody
  public Jqgrid findFactorysByName(Jqgrid jqgrid) {
    try {
      // if (filters == null) {
      // filters = new Filter();
      // }
      // filters.setGroupOp(FilterGroupOption.AND);
      String factoryName = HttpUtils.getParam("factoryName");
      SearchRule sr = new SearchRule("factoryName", SearchRuleOption.cn, factoryName);
      jqgrid.addRule(sr);
      // gAddress = goodAddressBiz.findByJqgrid(0, 10, filters, null);
      Page<GoodAddress> gAddress = goodAddressBiz.findByJqgrid(jqgrid);
      return jqgrid;
    } catch (QueryException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 新增报关
   *
   * @param declaration 报关信息
   * @param shipper 供应商信息
   */
  @RequestMapping(value = "/business-add", params = "bizType=D")
  @ResponseBody
  public Result add(Declaration declaration, Contacter shipper, String bizState, String isSubmit,
      String sfdTempId) {
    return add(null, null, declaration, shipper, bizState, isSubmit, sfdTempId);
  }

  /**
   * 添加新的业务//存为草稿
   */
  // @RequestMapping("/business-add")
  // @ResponseBody
  private synchronized Result add(Booking book, Trail trial, Declaration declare, Contacter shipper,
      String bizState, String isSubmit, String sfdTempId) {
    Result msg;
    String id = "";
    Result result = orderAction.v20Save(declare, sfdTempId);
    String businessId = declare.getBusinessId();
    if (!result.getResult()) {
      return result;
    }
    Map<String, Object> data = new HashMap<>();
    data.put("id", declarationBiz.findIdByBusinessId(businessId));
    data.put("businessId", businessId);
    if ("0".equals(bizState)) {
      msg = Result.newSuccessInstance(MsgConstants.SAVA_SUECCES_Draft, data);
    } else {
      isSubmit = "1";
      data.put(isSubmit, isSubmit);
      msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, data);
    }
    return msg;
  }

  @Resource
  SuiFuDanBiz suiFuDanBiz;

  @RequestMapping("/business-updateSuiFuDan")
  private void updateSuiFuDan(Declaration d, String sfdTempId) {
    // luob add sfd
    if (StringUtils.isNotEmpty(sfdTempId)) {
      List<SuiFuDan> sfdDatas = suiFuDanBiz.findEntityByHql(
          "select t from com.mrd.gtimp.business.entity.SuiFuDan t where t.temp_id='" + sfdTempId
              + "' ",
          0, 1000, null);
      if (null != sfdDatas && sfdDatas.size() > 0) {
        for (SuiFuDan suiFuDan : sfdDatas) {
          suiFuDan.setDeclaration(d);
        }
        try {
          suiFuDanBiz.getBaseRepository().saveOrUpdateEntities(sfdDatas);
        } catch (SaveException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 保存或者提交修改后的业务信息
   *
   * @param declare 修改后的报关单
   * @param summitBiz 是否是提交
   */
  @RequestMapping("/business-edit")
  @ResponseBody
  public Result edit(Declaration declare, @RequestParam(required = false) String summitBiz) {
    if (declare != null
        && jedisClientCluster.get("lock_decla_" + declare.getId(), String.class) != null) {
      return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
    }
    Result msg;
    try {
      if ("Y".equals(summitBiz)) {
        msg = orderAction.v20Submit(declare);
      } else {
        msg = orderAction.v20Save(declare);
      }
      if (!msg.getResult()) {
        return msg;
      }
      Map<String, Object> rsData = new HashMap<>();
      if (declare != null) {
        rsData.put("id", declare.getId());
        rsData.put("businessId", declare.getBusinessId());
      }
      msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES_ORDER, rsData);
      if (StringUtils.isNoneEmpty(summitBiz)) {
        if (null != declare && StringUtils.isNotEmpty(declare.getId())) {
          List<String> declara_ids = new ArrayList<>();
          declara_ids.add(declare.getId());
          dAction.setDeclaration_ids(declara_ids);
        }
        rsData.put("isSubmit", "1");
        msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, rsData);
      }
    } catch (Exception e) {
      e.printStackTrace();
      msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL, e.getMessage());
    }
    return msg;
  }

  @RequestMapping("/business-businessList")
  public String businessList() {
    return "/gtimp/business/businessList";
  }

  @Autowired
  private FundFlowBiz fundFlowBiz;

  /**
   * 转到农行支付
   */
  @RequestMapping("/business-payMent")
  public String payMent(String pay_id, String paymentType) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("billNo", pay_id);
    int billCount = 0;
    try {
      billCount = fundFlowBiz
          .findEntityCountBySql("select 1 from T_BIZ_FUND_FLOW where BILL_NO=:billNo", parameters);
    } catch (QueryException e1) {
      e1.printStackTrace();
    }
    /**
     * fix支付漏洞，确保银行转账已到账，或者余额扣款成功
     */
    if (paymentABCBiz.queryABCPayStatus(pay_id) || billCount > 0) {
      payMent = "error";
      return "payMent";
    }

    // 获取报关订单的信息
    String hql = "from com.mrd.gtimp.business.entity.DeclarationFree free where free.pay_id = '"
        + pay_id + "'";
    declarationFrees = declarationFreeBiz.findEntityByHql(hql, 0, 50, null);
    if (declarationFrees != null && declarationFrees.size() > 0) {
      DeclarationFree free = declarationFrees.get(0);
      if ("2".equals(paymentType)) {
        if (fundFlowBiz.findCurrentBalance(LoginUtil.getLoginUser().getCompany().getId()) < Double
            .parseDouble(free.getSum_free())) {
          payMent = "balance_error";
        } else {
          fundFlowBiz.addPayFlow(LoginUtil.getLoginUser().getCompany(),
              Double.parseDouble(free.getSum_free()), FundIETypeEnum.DC_PAY, pay_id,
              free.getDeclaration().getSupCompany());
          payMent = "success";
        }
      } else {
        // 生成支付请求 根据支付请求
        // 根据支付请求的结果，跳转支付页面 free.getSum_free()
        // free.setSum_free("0.1");
        Map<String, String> paymentRequestResult = paymentABCBiz.requestForPayment(free.getPay_id(),
            free.getSum_free(), "报关单费用", paymentType);
        if (paymentRequestResult != null
            && KEY_request_result_success.endsWith(paymentRequestResult.get(KEY_request_result))) {
          payMent = paymentRequestResult.get(KEY_paymentURL);
        } else {
          payMent = "error";
        }
      }
    } else {
      payMent = "error";
    }
    return payMent;
  }

  /**
   * 接收农行返回的支付结果
   */
  @RequestMapping("/business-receiveABCPayResponse")
  public String receiveABCPayResponse(String MSG) {
    try {
      // reponse.sendRedirect("/gtimp/index.do");
      // String msg = request.getParameter("MSG");
      System.out.println("银行通知系统");
      boolean isResult = paymentABCBiz.receiveABCPayResponse(MSG);
      if (isResult)
        return "redirect:/bussion/showPayResult?isSuccess=true";
      else
        return "redirect:/bussion/showPayResult?isSuccess=false";
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 接收支付平台返回的支付结果
   *
   * @return 处理结果
   */
  @RequestMapping("business-receivePaymentPlatformResp")
  @ResponseBody
  public String receivePaymentPlatformResponse() {
    try {
      InputStream is = HttpUtils.getRequest().getInputStream();
      String responseJsonStr = IOUtils.toString(is, "UTF-8"); // 支付平台反馈的支付结果 字符串信息 json格式
      return paymentPlatformBiz.resolveJsonStrFromPaymentPlatform(responseJsonStr).getResult()
          .toString();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 接收支付宝在线支付结果
   *
   * @return 处理结果
   */
  @RequestMapping("business-receivePaymentPlatformAliOnlinePayResp")
  public String receivePaymentPlatformAliOnlinePayResp(Model model, HttpServletRequest request) {
    Result result = paymentPlatformBiz.resolveRequestFromPaymentPlatform(request);
    if (result.getResult()) {
      return "/gtimp/fundAjustment/pay_success";
    }
    model.addAttribute("msg", result.getMsg());
    return "/gtimp/fundAjustment/pay_fail";
  }

  /**
   * 根据预付款编号询问银行支付结果
   */
  @RequestMapping("askBank4pay")
  public String askPayResultFromBank(String payId) {
    try {
      System.out.println(payId + ",开始询问银行");
      paymentABCBiz.askPayResultFromBank(payId);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 显示银行通知结果
   */
  @RequestMapping("showPayResult")
  public String showPayResult(String isSuccess) {
    return "/gtimp/business/paySuccess";
  }

  /**
   * 接收农行返回的支付结果,old
   */
  @SuppressWarnings("unused")
  @Deprecated
  @RequestMapping("/business-receiveABCPayResponse2")
  private String receiveABCPayResponse2() {
    /*
     * try { pay_id = paymentABCBiz.receiveABCPayResponse(MSG); // 记录支付结果 String hql =
     * "from com.mrd.gtimp.business.entity.DeclarationFree free where free.pay_id = '" + pay_id +
     * "'"; declarationFrees = new ArrayList<DeclarationFree>(); declarationFrees =
     * declarationFreeBiz.findEntityByHql(hql, 0, 100, null); declaration_ids = new
     * ArrayList<String>(); if(declarationFrees != null && declarationFrees.size() > 0) {
     * for(DeclarationFree free : declarationFrees) { free.setPay_comfirm("1"); free.setPay_time(new
     * Date()); declarationFreeBiz.saveOrupdateEntity(free);
     * declaration_ids.add(free.getDeclaration().getId()); if(free.getFree() != null &&
     * !"".equals(free.getFree())) { if("0.0".equals(free.getFree()) || "0".equals(free.getFree()))
     * { dAction.setId(free.getDeclaration().getId()); dAction.setPayment_Type("2");
     * dAction.updatePaymentType(); } else { dAction.setId(free.getDeclaration().getId());
     * dAction.setPayment_Type("1"); dAction.updatePaymentType(); } } log.info("支付成功，订单的pay_id ==" +
     * pay_id); log.info("订单的 订单号：" + free.getDeclaration().getId()); } payFree =
     * declarationFrees.get(0).getSum_free(); } dAction.setDeclaration_ids(declaration_ids);
     * dAction.bizConfirm(); } catch (SaveException e) { e.printStackTrace(); }
     */
    return "/gtimp/business/paySuccess";
  }

  /**
   * 根据declaration_id 获取支付id
   *
   * @param id 要修改单证的id
   */
  @RequestMapping("/business-getPayId")
  @ResponseBody
  public Result getPayId(String id) {
    Result msg;
    String hql =
        "from com.mrd.gtimp.business.entity.DeclarationFree free where free.declaration.id = '"
            + declareStr + "'";
    declarationFrees = new ArrayList<DeclarationFree>();
    declarationFrees = declarationFreeBiz.findEntityByHql(hql, 0, 100, null);
    if (declarationFrees.size() > 0 && declarationFrees.get(0) != null
        && declarationFrees.get(0).getPay_id() != null
        && !"".equals(declarationFrees.get(0).getPay_id())) {
      id = declarationFrees.get(0).getPay_id();
      msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
    } else {
      msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
    }
    return msg;
  }

  /**
   * 定时查询订单支付状态
   *
   * @param id 要修改单证的id
   */
  @RequestMapping("/business-queryAbcPayMentStatus")
  @ResponseBody
  public Result queryAbcPayMentStatus(String id, String pay_id) {
    Result msg;
    Boolean status = paymentABCBiz.queryABCPayStatus(pay_id);
    if (status) {// 支付成功
      id = pay_id;
      msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
    } else {// 尚未支付
      msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
    }
    return msg;
  }

  /**
   * 支付成功页面 沿用原有的支付成功页面 paySuccess.jsp 添加判断参数
   */
  @RequestMapping("/business-payAbcSuccess")
  public String payAbcSuccess(String payment_Type, String pay_id) {
    return "/gtimp/business/paySuccess";
  }

  /**
   * 支付失败处理 待开发
   */
  public String payAbcError() {
    return "msg";
  }

  /**
   * 从历史业务数据载入三种业务数据
   */
  public String businessListForLoadBiz() {
    return "businessListForLoadBiz";
  }

  /**
   * 模板选择界面 从历史业务数据载入booking业务数据
   */
  public String bookingListForLoadBiz() {
    return "bookingListForLoadBiz";
  }

  /**
   * 模板选择界面 从历史业务数据载入trail业务数据
   */
  public String trailListForLoadBiz() {
    return "trailListForLoadBiz";
  }

  /**
   * 模板选择界面 从历史业务数据载入declaration业务数据
   */
  public String declarationListForLoadBiz() {
    return "declarationListForLoadBiz";
  }

  // 找出业务列表
  @RequestMapping("/business-findBaseBusinessInfo")
  @ResponseBody
  public String findBaseBusinessInfo(Jqgrid jqgrid) {
    try {
      Filter filters = jqgrid.getFilters();
      if (filters == null) {
        filters = new Filter();
        filters.setGroupOp(FilterGroupOption.AND);
      }
      String listCase = "";
      listCase = "select distinct aa.business_id as business_id, c.company_name as comName, "
          + "aa.ctime as ctime, a.b_chn_name as bookState, a2.b_chn_name as trailState, "
          + "a1.b_chn_name as declareState, aa.id  "
          + "from t_biz_base_business aa left join (select t.business_id, b.state, bas.b_chn_name "
          + "from t_biz_base_business t join t_biz_booking b on b.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = b.state) a on a.business_id = aa.business_id "
          + "left join (select t.business_id, d.state, bas.b_chn_name from t_biz_base_business t "
          + "join t_biz_declaration d on d.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = d.state) a1 on a1.business_id = aa.business_id "
          + "left join (select t.business_id, tr.state, bas.b_chn_name from t_biz_base_business t "
          + "join t_biz_trail tr on tr.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = tr.state) a2 on a2.business_id = aa.business_id "
          + "left join t_biz_contacter c on c.id = aa.real_customer_id where 1=1 ";
      String whereCase = "";
      whereCase =
          "and aa.customer_com_id = '" + LoginUtil.getLoginUser().getCompany().getId() + "'";
      if (null != filters.getRules() && filters.getRules().size() > 0) {
        for (SearchRule sr : filters.getRules()) {
          String field = sr.getField();
          Object data = sr.getData();
          whereCase = whereCase + " and " + field + " like '%" + data + "%' ";
        }
      }
      String countCase = "select count(distinct aa.business_id) "
          + "from t_biz_base_business aa left join (select t.business_id, b.state, bas.b_chn_name "
          + "from t_biz_base_business t join t_biz_booking b on b.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = b.state) a on a.business_id = aa.business_id "
          + "left join (select t.business_id, d.state, bas.b_chn_name from t_biz_base_business t "
          + "join t_biz_declaration d on d.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = d.state) a1 on a1.business_id = aa.business_id "
          + "left join (select t.business_id, tr.state, bas.b_chn_name from t_biz_base_business t "
          + "join t_biz_trail tr on tr.id = t.id "
          + "join t_sys_base bas on bas.b_identifier = tr.state) a2 on a2.business_id = aa.business_id "
          + "left join t_biz_contacter c on c.id = aa.real_customer_id where 1=1 " + whereCase;
      listCase = listCase + whereCase + " order by aa.business_id desc ";

      List<Object> countList =
          businessBiz.findObjectBySql(countCase, 0, 10, new HashMap<String, Object>());
      List<Object> list = businessBiz.findObjectBySql(listCase,
          jqgrid.getPage().getPageNumber() + 1, jqgrid.getPage().getPageSize(), null);
      if (list != null && list.size() > 0) {
        List<BusinessDto> busiDtos = new ArrayList<BusinessDto>();
        for (Object o : list) {
          Object[] os = (Object[]) o;
          BusinessDto dto = new BusinessDto();
          dto.setBusiId(os[0].toString());
          dto.setCustomerName(os[1] == null ? "" : os[1].toString());
          dto.setCtime((Date) os[2]);
          dto.setBookState(os[3] == null ? "" : os[3].toString());
          dto.setTrailState(os[4] == null ? "" : os[4].toString());
          dto.setDeclareState(os[5] == null ? "" : os[5].toString());
          dto.setId(os[6].toString());
          busiDtos.add(dto);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  // 找出业务列表
  // public String findBaseBusinessInfo() {
  // try {
  // if(filters == null) {
  // filters = new Filter();
  // filters.setGroupOp(FilterGroupOption.AND);
  // }
  // String listCase =
  // "select distinct t.businessId, t.shipper.company, t.shipper.phone, t.CTIME from ";
  // String whereCase = "";
  // whereCase = " com.mrd.gtimp.business.entity.BaseBusiness t where 1=1 "
  // + " and t.customer.id='" + user.getCompany().getId() + "'";
  // if(null != filters.getRules() && filters.getRules().size() > 0) {
  // for(SearchRule sr : filters.getRules()) {
  // String field = sr.getField();
  // Object data = sr.getData();
  // whereCase = whereCase + " and " + field + " like '%" + data + "%' ";
  // }
  // }
  // // if("load".equals(loadPage)){
  // // whereCase = whereCase +
  // " and t.shipper.company.state in('BS04','DS04','TS04')";
  // // }
  // String countCase = "select count(distinct t.businessId) from " +
  // whereCase
  // + " and customer.id='" + user.getCompany().getId() + "'";
  // listCase = listCase + whereCase + " order by t.businessId desc";
  // List<Object> countlist = businessBiz
  // .findObjectByHql(countCase, 0, 10, new HashMap<String, Object>());
  // page = initPage(Integer.parseInt(countlist.get(0).toString()));
  // List<Object> list = businessBiz
  // .findObjectByHql(listCase, page.getCurrentPageStartNo(),
  // page.getPageSize(), new
  // HashMap<String, Object>());
  // if(null != list && list.size() > 0) {
  // busiDtos = new ArrayList<BusinessDto>();
  // for(Object o : list) {
  // Object[] os = (Object[]) o;
  // BusinessDto dto = new BusinessDto();
  // dto.setBusiId(os[0].toString());
  // dto.setCustomerName(os[1] == null ? "" : os[1].toString());
  // dto.setCtime((Date) os[3]);
  // dto.setBookState("点击详细");
  // dto.setTrailState("点击详细");
  // dto.setDeclareState("点击详细");
  // busiDtos.add(dto);
  // }
  // }
  // } catch (QueryException e) {
  // e.printStackTrace();
  // }
  // return SUCCESS;
  // }

  /**
   * 根据bizId和bizType读取历史业务数据
   *
   * @param bizId 业务id
   * @param bizType 业务类型
   */
  @RequestMapping("/business-loadBizFromHistoryData")
  @ResponseBody
  public LoadModelJsonView loadBizFromHistoryData(String bizId, String bizType) {
    LoadModelJsonView loadModelJsonView = new LoadModelJsonView();
    try {
      if (StringUtils.isNotEmpty(bizId)) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("bizId", bizId);
        parameters.put("bizType", bizType);
        String sql;
        if (BaseTypeConstant.TRAIL_TYPE.equals(bizType)
            || BaseTypeConstant.DECLARATION_TYPE.equals(bizType)
            || BaseTypeConstant.BOOKING_TYPE.equals(bizType)) {
          sql =
              "select id,type from T_BIZ_BASE_BUSINESS_MODEL where BUSINESS_ID=:bizId and TYPE=:bizType";
        } else {// all
          parameters.remove("bizType");
          sql = "select id,type from T_BIZ_BASE_BUSINESS_MODEL where BUSINESS_ID=:bizId";
        }
        List<Object> bus = bookBiz.findObjectBySql(sql, 1, 3, parameters);
        if (null != bus && bus.size() > 0) {
          for (Object b : bus) {
            Object[] bb = (Object[]) b;
            if (BaseTypeConstant.BOOKING_TYPE.equals(bb[1])) {
              loadModelJsonView.setBook(new Booking());
              loadModelJsonView.getBook().setId(bb[0] == null ? "" : bb[0].toString());
            } else if (BaseTypeConstant.TRAIL_TYPE.equals(bb[1])) {
              loadModelJsonView.setTrial(new Trail());
              loadModelJsonView.getTrial().setId(bb[0] == null ? "" : bb[0].toString());
            } else if (BaseTypeConstant.DECLARATION_TYPE.equals(bb[1])) {
              loadModelJsonView.setDeclare(new Declaration());
              loadModelJsonView.getDeclare().setId(bb[0] == null ? "" : bb[0].toString());
            }
          }

        }
        // sql = "select id,name,phone,company_name,address from T_BIZ_CONTACTER_MODEL where
        // id in (select distinct(real_customer_id) from T_BIZ_BASE_BUSINESS_MODEL where
        // business_id =:bizId)";
        // parameters.remove("bizType");
        // List<Object> shipperObj = bookBiz.findObjectBySql(sql, 1, 1, parameters);
        // if (shipperObj != null) {
        // Object[] shipperObjData = (Object[]) shipperObj.get(0);
        // Contacter shipper = new Contacter();
        // shipper.setId(shipperObjData[0] == null ? "" : shipperObjData[0].toString());
        // shipper.setName(shipperObjData[1] == null ? "" : shipperObjData[1].toString());
        // shipper.setPhone(shipperObjData[2] == null ? "" : shipperObjData[2].toString());
        // shipper.setCompany(shipperObjData[3] == null ? ""
        // : shipperObjData[3].toString());
        // shipper.setAddress(shipperObjData[4] == null ? ""
        // : shipperObjData[4].toString());
        // loadModelJsonView.setShipper(shipper);
        // }
        return loadModelJsonView;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  // 查找各种业务当前的状态
  @RequestMapping("/business-findState")
  public String findState() {
    String busiId = HttpUtils.getParam("busiId");
    String type = HttpUtils.getParam("type");
    if (StringUtils.isNotEmpty(busiId) && StringUtils.isNotEmpty(type)) {
      String hql = "";
      if ("1".equals(type)) {
        hql =
            "select val.chn from com.mrd.gtimp.business.entity.Booking book, com.mrd.gtimp.business.entity.BaseBusiness busi, com.mrd.gtimp.base.entity.SystemValue val "
                + " where book.id=busi.id and book.bookingState=val.identifier and busi.businessId='"
                + busiId + "'";
      } else if ("2".equals(type)) {
        hql =
            "select val.chn from com.mrd.gtimp.business.entity.Trail trail, com.mrd.gtimp.business.entity.BaseBusiness busi, com.mrd.gtimp.base.entity.SystemValue val "
                + " where trail.id=busi.id and trail.trailState=val.identifier and busi.businessId='"
                + busiId + "'";
      } else if ("3".equals(type)) {
        hql =
            "select val.chn from com.mrd.gtimp.business.entity.Declaration decla, com.mrd.gtimp.business.entity.BaseBusiness busi, com.mrd.gtimp.base.entity.SystemValue val "
                + " where decla.id=busi.id and decla.state=val.identifier and busi.businessId='"
                + busiId + "'";
      }
      try {
        List<Object> objs = businessBiz.findObjectByHql(hql, 0, 10, null);
        if (null != objs && objs.size() > 0) {
          state = objs.get(0).toString();
        } else {
          state = "没有状态";
        }
      } catch (QueryException e) {
        e.printStackTrace();
      }
    }
    //// TODO: 2016/8/13
    return null;
  }

  @RequestMapping("/business-getBusinessDetailsByBusiId")
  public String getBusinessDetailsByBusiId(Booking book, Trail trial, Declaration declare,
      BaseBusiness business) {
    try {
      // TODO: 2016/8/17 不在继承需要重新实现
      // ports = super.setResultByBaseType(BaseTypeConstant.PORT_TYPE);
      // businessType = super.setResultByBaseType(BaseTypeConstant.BOOKING_BIZ_TYPE);
      String businessId = HttpUtils.getParam("businessId");
      if (StringUtils.isNotEmpty(businessId)) {
        List<BaseBusiness> bus = businessBiz.findEntityByHql(
            "from com.mrd.gtimp.business.entity.BaseBusiness where businessId='" + businessId + "'",
            0, 10, null);
        business = bus.get(0);
        if (null != bus && bus.size() > 0) {
          for (BaseBusiness b : bus) {
            if (BaseTypeConstant.BOOKING_TYPE.equals(b.getType())) {
              book = bookBiz.findEntityById(b.getId());
              // goods = book.getGoodses();
              /*
               * for(Goods g : goods) { System.out.println(g.getName()); }
               */
            } else if (BaseTypeConstant.TRAIL_TYPE.equals(b.getType())) {
              trial = trailBiz.findEntityById(b.getId());
            } else if (BaseTypeConstant.DECLARATION_TYPE.equals(b.getType())) {
              declare = declaBiz.findEntityById(b.getId());
            }
          }

        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/businessDetails";
  }

  /**
   * @param shipper 发货人
   */
  @RequestMapping("/business-main")
  public String main(HttpSession session, Contacter shipper, Model model) {
    User u = LoginUtil.getLoginUser();
    shipper = new Contacter();
    String name1 = u.getName();
    if (null != u.getDepts() && null != u.getDepts().get(0).getCompany()) {
      String companyName1 = u.getDepts().get(0).getCompany().getName();
      String address1 = u.getDepts().get(0).getCompany().getAddress();
      String fax1 = u.getDepts().get(0).getCompany().getFax();
      String phone1 = u.getMobile();
      Filter filter = new Filter();
      filter.addRule(new SearchRule("name", SearchRuleOption.eq, name1));
      filter.addRule(new SearchRule("company", SearchRuleOption.eq, companyName1));
      filter.addRule(new SearchRule("address", SearchRuleOption.eq, address1));
      filter.addRule(new SearchRule("fax", SearchRuleOption.bn, fax1));
      filter.addRule(new SearchRule("phone", SearchRuleOption.eq, phone1));
      List<Contacter> contacter = null;
      try {
        contacter = contacterBiz.findEntityByFilter(0, 10, filter, null);
      } catch (QueryException e) {
        e.printStackTrace();
      }
      if (CollectionUtils.isNotEmpty(contacter)) {
        shipper.setId(contacter.get(0).getId());
      }
      shipper.setName(name1);
      shipper.setCompany(companyName1);
      shipper.setAddress(address1);
      shipper.setFax(fax1);
      shipper.setPhone(u.getMobile());
      shipper.setEmail(u.getEmail());
      model.addAttribute("shipper", shipper);
    }
    return "/gtimp/business/business";
  }

  @RequestMapping("/business-booking")
  public String booking(Booking book) {
    // TODO: 2016/8/17 不在继承需要重新实现
    // businessType = super.setResultByBaseType(BaseTypeConstant.BOOKING_BIZ_TYPE);
    // ports = super.setResultByBaseType(BaseTypeConstant.PORT_TYPE);
    // units = super.setResultByBaseType(BaseTypeConstant.UNIT_TYPE);
    // currencys =
    // super.setResultByBaseType(BaseTypeConstant.CURRENCY_TYPE);
    // countries = super.setResultByBaseType(BaseTypeConstant.COUNTRY_TYPE);
    // deals = super.setResultByBaseType(BaseTypeConstant.DEAL_TYPE);
    try {
      // 有id传入则进入修改状态
      if (book != null && StringUtils.isNotEmpty(book.getId())) {
        book = bookBiz.findEntityById(book.getId());
        if (book != null && "1".equals(clearPk)) {
          book.clearPk();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/booking";
  }

  @RequestMapping("/business-supBooking")
  public String supBooking(Booking book) {
    // TODO: 2016/8/17 不在继承需要重新实现
    // businessType = super.setResultByBaseType(BaseTypeConstant.BOOKING_BIZ_TYPE);
    // ports = super.setResultByBaseType(BaseTypeConstant.PORT_TYPE);
    // units = super.setResultByBaseType(BaseTypeConstant.UNIT_TYPE);
    // currencys =
    // super.setResultByBaseType(BaseTypeConstant.CURRENCY_TYPE);
    // countries = super.setResultByBaseType(BaseTypeConstant.COUNTRY_TYPE);
    // deals = super.setResultByBaseType(BaseTypeConstant.DEAL_TYPE);
    try {
      // 有id传入则进入修改状态
      if (book != null && StringUtils.isNotEmpty(book.getId())) {
        book = bookBiz.findEntityById(book.getId());
        if (book != null && "1".equals(clearPk)) {
          book.clearPk();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/supBooking";
  }

  @RequestMapping("/business-trail")
  public String trail(Trail trial) {
    // 有id传入则进入修改状态
    List<Container> containers = null;
    try {
      if (trial != null && StringUtils.isNotEmpty(trial.getId())) {
        trial = trailBiz.findEntityById(trial.getId());
        if (trial != null && "1".equals(clearPk)) {
          trial.clearPk();
        }
        // 临时存放柜id
        StringBuffer container_tmp = new StringBuffer();
        containers = new ArrayList<Container>();
        // 获取所有的柜，并且对柜进行去重，便于页面去重
        if (trial != null && trial.getGdes() != null) {
          for (GoodAddress ga : trial.getGdes()) {
            if (ga.getContainers() != null) {
              for (Container container : ga.getContainers()) {
                if (container_tmp.indexOf(container.getId()) == -1) {
                  container_tmp.append(container.getId()).append(",");
                  containers.add(container);
                }
              }
            }
            // System.out.println(ga.getCtNumType());
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/trail";
  }

  /**
   * 拖车模板获取数据
   */
  @RequestMapping("/business-trailModel")
  public String trailModel(TrailModel trailModel) {
    List<Container> containers = null;
    try {
      String id = HttpUtils.getParam("id");
      if (!"".equals(id) || id != null) {
        // if(trailModel != null &&
        // StringUtils.isNotEmpty(trailModel.getId())) {
        trailModel = trailModelBiz.findEntityById(id);
        // if(trailModel != null && "1".equals(clearPk)) {
        // trailModel.clearPk();
        // }
        // 临时存放柜id
        StringBuffer container_tmp = new StringBuffer();
        containers = new ArrayList<Container>();
        // 获取所有的柜，并且对柜进行去重，便于页面去重
        if (trailModel != null && trailModel.getGdes() != null) {
          for (GoodAddressModel ga : trailModel.getGdes()) {
            if (ga.getContainers() != null) {
              for (Container container : ga.getContainers()) {
                if (container_tmp.indexOf(container.getId()) == -1) {
                  container_tmp.append(container.getId()).append(",");
                  containers.add(container);
                }
              }
            }
            // System.out.println(ga.getCtNumType());
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/trail";
  }

  // 生成的报关单
  @RequestMapping("/business-declaration")
  public String declaration(Model model) {
    try {
      Declaration declare = null;
      String declareStr = HttpUtils.getParam("declareStr");
      if (StringUtils.isNoneEmpty(declareStr)) {
        // 解码 这是前台的导入exl表格时页面传回的数据
        String declareStr1 = URLDecoder.decode(declareStr, "UTF-8");
        JSONObject jsonobj = JSONObject.fromObject(declareStr1);
        JSONArray array = jsonobj.getJSONArray("commodities");
        List<Commodity> list = new ArrayList<Commodity>();
        for (int i = 0; i < array.size(); i++) {
          JSONObject obj = (JSONObject) array.get(i);
          Commodity c = (Commodity) JSONObject.toBean(obj, Commodity.class);
          if (c != null) {
            list.add(c);
          }
        }
        declare = (Declaration) JSONObject.toBean(jsonobj, Declaration.class);
        declare.setCommodities(list);
        declare.setExport_date(null);
      }
      // 如果有传入id则进入修改状态
      // if(declare != null && StringUtils.isNotEmpty(declare.getId())) {
      // declare = declaBiz.findEntityById(declare.getId());
      // if(declare != null && "1".equals(clearPk)) {
      // declare.clearPk();
      // }
      // }
      String id = HttpUtils.getParam("id");
      if (id != null && !"".equals(id)) {
        declare = declaBiz.findEntityById(id);
        List<SuiFuDan> sfdDatas = suiFuDanBiz.findEntityByHql(
            "select t from com.mrd.gtimp.business.entity.SuiFuDan t where t.declaration.id='" + id
                + "' ",
            0, 1000, null);
        String sfdStr = "";
        String sfdValueStr = "";
        for (SuiFuDan suiFuDan : sfdDatas) {
          sfdStr += suiFuDan.getSuifudan_co() + suiFuDan.getSuifudan_co_cn() + ",";
          sfdValueStr += suiFuDan.getSuifudan_no() + ",";
        }
        declare
            .setSuifudan(sfdStr.length() > 0 ? sfdStr.substring(0, sfdStr.length() - 1) : sfdStr);
        declare.setSuifudanValue(
            sfdValueStr.length() > 0 ? sfdValueStr.substring(0, sfdValueStr.length() - 1)
                : sfdValueStr);
        List<Commodity> nCommodities = repackCommodities(declare.getCommodities());
        declare.setCommodities(nCommodities);
      }
      model.addAttribute("declare", declare);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/declaration/declarationInfoForView";
  }

  /**
   * 报关下单主页面
   */
  @RequestMapping("/business-declarationMain")
  public String declarationMain(Model model, String id, String modelType, String clearPk,
      String isRecord) {
    String returnWebPage = "/gtimp/business/declarationMain";
    if (StringUtils.isBlank(id)) {
      model.addAttribute("modelType", modelType);
      return returnWebPage;
    }
    try {
      List<RejectContent> rejectContentList = null;
      if ("1".equals(modelType)) {
        DeclarationModel declareModel = declaModelBiz.findEntityById(id);
        declareModel.setActionChain(Declaration.ChainModel.userModel, false);
        model.addAttribute("declareModel", declareModel);
        model.addAttribute("modelType", modelType);
      } else {
        Declaration declare = declaBiz.findEntityById(id);
        List<Commodity> ncommodities = repackCommodities(declare.getCommodities());
        declare.setCommodities(ncommodities);
        if ("1".equals(clearPk)) {
          declare.clearPk();
        }
        // 驳回原因
        // rejectContentList = rejectContentBiz
        // .findEntityByHql("from com.mrd.gtimp.business.entity.RejectContent rejectContent
        // where rejectContent.bid = '"
        // + id + "'", 0, 10, null);
        model.addAttribute("declare", declare);
        model.addAttribute("rejectContentList", declare.getRejectContents());
        model.addAttribute("modelType", modelType);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return returnWebPage;
  }

  /**
   * 重新包装commodity
   *
   * @param commodities 待包装的commodity
   * @return 一包装
   */
  private List<Commodity> repackCommodities(List<Commodity> commodities) {
    List<Commodity> newCommodities = new ArrayList<>();
    for (int i = 0; i < commodities.size(); i++) {
      int index_num = i + 1;
      newCommodities.addAll(commodities.stream()
          .filter(c -> (index_num + "").equals(c.getIndex_num())).collect(Collectors.toList()));
    }
    return newCommodities;
  }

  /**
   * 装箱单主页面
   */
  @RequestMapping("/business-declarationPackingList")
  public String declarationPackingList(Model model, String id) {
    try {
      // 如果有传入id则进入修改状态
      if (StringUtils.isNoneEmpty(id)) {
        Declaration declare = declaBiz.findEntityById(id);
        List<Commodity> nCommodities = repackCommodities(declare.getCommodities());
        declare.setCommodities(nCommodities);
        model.addAttribute("declare", declare);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/declarationPackingList";
  }

  private String commodity_id = "";

  private String goods_number = "";

  /**
   * 装箱单明细页
   */
  @RequestMapping("/business-declarationPackingDetailed")
  public String declarationPackingDetailed(PackingListDetailed packingListDetailed, Model model) {
    List<PackingListDetailed> packingListDetaileds = new ArrayList<>();
    commodity_id = HttpUtils.getParam("commodity_id");
    goods_number = HttpUtils.getParam("goods_number");
    String hql = "from com.mrd.gtimp.business.entity.PackingListDetailed where COMMODITY_ID_ ='"
        + commodity_id + "'";
    try {
      //// TODO: 2016/9/6 装箱单明细表 不存在
      packingListDetaileds = packingListDetailedBiz.findEntityByHql(hql, 0, 0, null);
      model.addAttribute("packingListDetaileds", packingListDetaileds);
      // packingListDetailed = packingListDetailedBiz.findEntityById(commodity_id);
      // model.addAttribute("packingListDetailed", packingListDetailed);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/declarationPackingDetailed";
  }

  @RequestMapping("/business-savePackingListDetailed")
  @ResponseBody
  public Result savePackingListDetailed(PackingListDetailed packingListDetailed) {
    Result msg;
    try {
      if (packingListDetailed.getId().equals("")) {
        packingListDetailed.setId(null);
      }
      packingListDetailedBiz.saveOrupdateEntity(packingListDetailed);
      msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
    } catch (SaveException e) {
      e.printStackTrace();
      msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL + e.getMessage());
    }
    return msg;
  }

  @RequestMapping("/business-delPackingListDetailed")
  @ResponseBody
  public Result delPackingListDetailed() {
    Result msg;
    String id = HttpUtils.getParam("id");
    if (id == null || id.equals("")) {
      msg = Result.newFailInstance(MsgConstants.DEL_FAIL);
    } else {
      try {
        PackingListDetailed packingListDetailed = new PackingListDetailed();
        packingListDetailed.setId(id);
        packingListDetailedBiz.delete(packingListDetailed);
        msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
      } catch (DeleteException e) {
        e.printStackTrace();
        msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
      }
    }
    return msg;
  }

  /**
   * 合同主页面
   */
  @RequestMapping("/business-declarationContract")
  public String declarationContract(Model model, String id) {
    Declaration declaration = findDeclarationForView(id);
    String comType = LoginUtil.getLoginUser().getCompany().getType();
    boolean isEdit = false;
    if (StringUtils.isNotEmpty(comType)
        && (comType.equalsIgnoreCase("CL") || comType.equalsIgnoreCase("CM"))
        && (declaration.getState()
            .equalsIgnoreCase(Declaration.DeclarationBusinessState.DRAFT_STATE)
            || (declaration.getState()
                .equalsIgnoreCase(Declaration.DeclarationBusinessState.ORDER_STATE)
                && declaration.getPayment_type().equalsIgnoreCase("0")))) {
      isEdit = true;
    }
    model.addAttribute("isEdit", isEdit);
    model.addAttribute("declare", declaration);
    return "/gtimp/business/declarationContract";
  }

  /**
   * 查找报关单，并对商品集合进行处理，用于展示
   */
  private Declaration findDeclarationForView(String id) {
    try {
      // 如果有传入id则进入修改状态
      if (StringUtils.isNotBlank(id)) {
        Declaration declare = declaBiz.findEntityById(id);
        declare.setCommodities(repackCommodities(declare.getCommodities()));
        return declare;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 发票主页面
   */
  @RequestMapping("/business-declarationInvoice")
  public String declarationInvoice(Model model, String id) {
    Declaration declaration = findDeclarationForView(id);
    model.addAttribute("declare", declaration);
    return "/gtimp/business/declarationInvoice";
  }

  /**
   * 有木质包装
   */
  @RequestMapping("/business-woodPackaging")
  public String woodPackaging(Declaration declare) {
    try {
      String id = HttpUtils.getParam("id");
      // 如果有传入id则进入修改状态
      if (id != null && !"".equals(id)) {
        declare = declaBiz.findEntityById(id);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/woodPackaging";
  }

  /**
   * 无木质包装
   */
  @RequestMapping("/business-noWoodPackaging")
  public String noWoodPackaging(Declaration declare, Model model) {
    try {
      String id = declare.getId();
      // 如果有传入id则进入修改状态
      if (id != null && !"".equals(id)) {
        declare = declaBiz.findEntityById(id);
        model.addAttribute("declare", declare);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/noWoodPackaging";
  }

  /**
   * 整体业务修改
   */
  @RequestMapping("/business-update")
  public String update(Jqgrid jqgrid, Booking book, Trail trial, Declaration declare,
      BaseBusiness business) {
    // http://localhost:8081/gtimp/business/business-update.do?businessId=BE20130122111824
    try {
      String businessId = HttpUtils.getParam("businessId");
      if (StringUtils.isNotEmpty(businessId)) {
        // List<BaseBusiness> bus = businessBiz
        // .findEntityByHql("from com.mrd.gtimp.business.entity.BaseBusiness where
        // businessId='"
        // + businessId + "'", 0, 10, null);
        jqgrid.addRule(new SearchRule("businessId", SearchRuleOption.eq, businessId));
        // List<BaseBusiness> bus = businessBiz.findByJqgrid(0, 10, filters, null);
        Page<BaseBusiness> bus = businessBiz.findByJqgrid(jqgrid);
        if (null != bus && bus.getSize() > 0) {
          business = bus.getContent().get(0);
          for (BaseBusiness b : bus) {
            if (BaseTypeConstant.BOOKING_TYPE.equals(b.getType())) {
              book = new Booking();
              book.setId(b.getId());
              book.setConfirmTime(b.getConfirmTime());
            } else if (BaseTypeConstant.TRAIL_TYPE.equals(b.getType())) {
              trial = new Trail();
              trial.setId(b.getId());
              trial.setConfirmTime(b.getConfirmTime());
            } else if (BaseTypeConstant.DECLARATION_TYPE.equals(b.getType())) {
              declare = new Declaration();
              declare.setId(b.getId());
              declare.setConfirmTime(b.getConfirmTime());
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/business-update";
  }

  /**
   * 处理单种业务修改
   *
   * @param id 要修改单证的id
   */
  @RequestMapping("/business-updateSingle")
  public String updateSingle(Model model, String id, String singleType, String identification) {
    try {
      // String businessId = HttpUtils.getParam("businessId");
      String companyId = LoginUtil.getLoginUser().getCompany().getId();
      if (StringUtils.isNotEmpty(id)) {
        Declaration declaration = declaBiz.findEntityById(id);
        // todo companyId.equals(declaration.getCustomer().getId()) ? 不符合逻辑
        // if (declaration.getCustomer() != null &&
        // companyId.equals(declaration.getCustomer().getId())) {
        if (declaration.getCustomer() != null) {
          model.addAttribute("declare", declaration);
        }
        model.addAttribute("id", id);
        model.addAttribute("singleType", singleType);
        model.addAttribute("identification", identification);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/business-update";
  }

  /**
   * 查看业务详细（新）
   *
   * @param id 要修改单证的id
   * @param singleType 修改页面的类型参数
   */
  @RequestMapping("/business-checkDetail")
  public String checkDetail(Jqgrid jqgrid, Booking book, Trail trial, Declaration declare,
      BaseBusiness business, String id, String singleType) {
    try {
      // String businessId = HttpUtils.getParam("id");
      if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(singleType)) {
        // filters = new Filter();
        // filters.setGroupOp(FilterGroupOption.AND);
        jqgrid.addRule(new SearchRule("id", SearchRuleOption.eq, id));
        jqgrid.addRule(new SearchRule("type", SearchRuleOption.eq, singleType));
        // List<BaseBusiness> bus = businessBiz.findByJqgrid(0, 10, filters, null);
        Page<BaseBusiness> bus = businessBiz.findByJqgrid(jqgrid);
        if (null != bus && bus.getSize() > 0) {
          business = bus.getContent().get(0);
          if (BaseTypeConstant.BOOKING_TYPE.equals(business.getType())
              && BaseTypeConstant.BOOKING_TYPE.equals(singleType)) {
            book = new Booking();
            book.setId(business.getId());
          } else if (BaseTypeConstant.TRAIL_TYPE.equals(business.getType())
              && BaseTypeConstant.TRAIL_TYPE.equals(singleType)) {
            trial = new Trail();
            trial.setId(business.getId());
          } else if (BaseTypeConstant.DECLARATION_TYPE.equals(business.getType())
              && BaseTypeConstant.DECLARATION_TYPE.equals(singleType)) {
            declare = new Declaration();
            declare.setId(business.getId());
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/business-checkDetail";
  }

  /**
   * 根据客户端上传的exl文件经过后台处理后导入到jsp页面上
   */
  @RequestMapping("/business-importBusiExl")
  public String importBusiExl(Booking book, Trail trial, Declaration declare) {
    FileInputStream is = null;
    Workbook workbook = null;
    // 作为一个标识
    identification = "importExl";
    try {
      String fileNameEnd = importExlFileName.substring(importExlFileName.lastIndexOf("."));
      if (!".xls".equals(fileNameEnd)) {
        return "";
      }
      is = new FileInputStream(importExlFile);
      workbook = Workbook.getWorkbook(is);
      // 工作表格的个数
      int sheetNumber = workbook.getNumberOfSheets();
      if (sheetNumber <= 0) {
        return "";
      }
      // 只读取前面的三个工作表
      for (int i = 0; i < sheetNumber; i++) {
        Sheet sheet = workbook.getSheet(i);
        int rows = sheet.getRows();// 用于在最后判断是否已经到头了
        if ("报关".equals(sheet.getName())) {
          declare = new Declaration();
          declare.setSupCompany(new Company());
          declare.getSupCompany().setName(sheet.getCell(1, 0).getContents());
          declare.setExport_port(sheet.getCell(1, 1).getContents());
          declare.setRecord_id(sheet.getCell(5, 1).getContents());
          // 日期类数据自己填写 不帮导入
          declare.setCompany_name(sheet.getCell(1, 2).getContents());
          declare.setTransport_mode(sheet.getCell(5, 2).getContents());
          declare.setTransport_na(sheet.getCell(7, 2).getContents());
          declare.setBl_no(sheet.getCell(9, 2).getContents());
          declare.setFahuo_company_name(sheet.getCell(1, 3).getContents());
          declare.setTrade_mode(sheet.getCell(5, 3).getContents());
          declare.setLevymode(sheet.getCell(7, 3).getContents());
          declare.setLc_type(sheet.getCell(9, 3).getContents());
          declare.setLicense_no(sheet.getCell(1, 4).getContents());
          declare.setArrived_country(sheet.getCell(4, 4).getContents());
          declare.setArrived_port(sheet.getCell(6, 4).getContents());
          declare.setGoods_addr(sheet.getCell(8, 4).getContents());
          declare.setApproval_no(sheet.getCell(1, 5).getContents());
          declare.setDeal_mode(sheet.getCell(4, 5).getContents());
          declare.setFreight1(sheet.getCell(6, 5).getContents());
          declare.setPremium1(sheet.getCell(8, 5).getContents());
          declare.setOtherfee1(sheet.getCell(10, 5).getContents());
          declare.setContract_no(sheet.getCell(1, 6).getContents());
          declare.setGoods_count(sheet.getCell(4, 6).getContents());
          declare.setGoods_package(sheet.getCell(6, 6).getContents());
          declare.setGross_weight(sheet.getCell(8, 6).getContents());
          declare.setNet_weight(sheet.getCell(10, 6).getContents());
          // 集装箱号报关页面没有 不进行导入
          declare.setSuifudan(sheet.getCell(4, 7).getContents());
          declare.setRemark(sheet.getCell(1, 8).getContents());
          List<Commodity> commodities = new ArrayList<Commodity>();
          for (int row = 11;; row++) {
            Commodity c = new Commodity();
            // Cell cell = sheet.getCell(1, row);
            // String str = cell.getContents();
            if (row >= rows) {
              break;
            }
            c.setCode_t(sheet.getCell(1, row).getContents());
            c.setRecord_id(sheet.getCell(2, row).getContents());
            c.setName(sheet.getCell(3, row).getContents());
            c.setGoods_mode(sheet.getCell(4, row).getContents());
            c.setDestination(sheet.getCell(5, row).getContents());
            c.setCount(sheet.getCell(6, row).getContents());
            c.setUnit(sheet.getCell(7, row).getContents());
            c.setCurrency(sheet.getCell(8, row).getContents());
            c.setTotal_price(sheet.getCell(9, row).getContents());
            c.setLevymode(sheet.getCell(10, row).getContents());
            commodities.add(c);
          }

          declare.setCommodities(commodities);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      workbook.close();
    }
    //// TODO: 2016/8/13 chain
    return null;
  }

  /**
   * 对重复的so号去重
   */
  @RequestMapping("/business-removeDuplicateSo")
  public String removeDuplicateSo(String str) {
    String[] s = str.split(",");

    TreeSet<String> tr = new TreeSet<String>();
    for (String element : s) {
      if (!"null".equals(element)) {
        tr.add(element);
      }
    }
    String[] s2 = new String[tr.size()];
    String so = "";
    for (int i = 0; i < s2.length; i++) {
      s2[i] = tr.pollFirst();// 从TreeSet中取出元素重新赋给数组
      so = so + s2[i] + ",";
    }
    if (!"".equals(so)) {
      so = so.substring(0, so.length() - 1);
    }
    return so;
  }

  /**
   * 用于导出(订舱 拖车 报关)单的exl 根据页面的传回来的id查询数据库获取数据进行导出
   */
  @RequestMapping("/business-createBusiExl")
  public String createBusiExl(Jqgrid jqgrid, Booking book, Trail trial, Declaration declare,
      CancelReason cancelReason, BaseBusiness busines) {
    WritableWorkbook writableWorkbook = null;
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
      this.exlFileName = sdf.format(new Date()) + ".xls";
      // ServletContext context =
      // ServletActionContext.getServletContext();
      // String dataDir = context.getRealPath("/WEB-INF");
      // String path = str1.substring(0, 7);
      ByteArrayOutputStream bos = new ByteArrayOutputStream(1024000);
      // OutputStream os = new FileOutputStream(dataDir + exlFileName);
      writableWorkbook = Workbook.createWorkbook(bos);
      int i = 0;
      String businessId = HttpUtils.getParam("businessId");
      if (businessId != null) {
        if (StringUtils.isNotEmpty(businessId)) {
          // List<BaseBusiness> bus = businessBiz
          // .findEntityByHql("from com.mrd.gtimp.business.entity.BaseBusiness where
          // businessId='"
          // + businessId + "'", 0, 10, null);
          jqgrid.addRule(new SearchRule("businessId", SearchRuleOption.eq, businessId));
          // List<BaseBusiness> bus = businessBiz.findByJqgrid(0, 10, filters, null);
          Page<BaseBusiness> bus = businessBiz.findByJqgrid(jqgrid);
          if (null != bus && bus.getSize() > 0) {
            busines = bus.getContent().get(0);
            for (BaseBusiness b : bus) {
              if (BaseTypeConstant.BOOKING_TYPE.equals(b.getType())) {
                book = new Booking();
                book = (Booking) b;
              } else if (BaseTypeConstant.TRAIL_TYPE.equals(b.getType())) {
                trial = new Trail();
                trial = (Trail) b;
              } else if (BaseTypeConstant.DECLARATION_TYPE.equals(b.getType())) {
                declare = new Declaration();
                declare = (Declaration) b;
              }
            }
          }
        }

      } else {

        if (book != null) {
          book = bookBiz.findEntityById(book.getId());
        }
        if (trial != null) {
          trial = trailBiz.findEntityById(trial.getId());
          List<CancelReason> list = cancelReasonBiz.findEntityByHql(
              "from com.mrd.gtimp.business.entity.CancelReason where bid = '" + trial.getId() + "'",
              0, 10, null);
          cancelReason = new CancelReason();
          for (CancelReason cr : list) {
            cancelReason.setCancelDate(cr.getCancelDate());
            cancelReason.setCancelPerson(cr.getCancelPerson());
            cancelReason.setContent(cr.getContent());
          }

        }
        if (declare != null) {
          declare = declaBiz.findEntityById(declare.getId());
        }
      }
      if (declare == null && trial == null && book == null) {
        return "";
      }
      // 生成名为订舱单的工作表
      if (book != null && book.getGoodses() != null) {
        WritableSheet sheet = writableWorkbook.createSheet("订舱", i);
        for (int k = 0; k < 14 + book.getGoodses().size(); k++) {
          sheet.setColumnView(k, 15);
          sheet.setRowView(k, 500);
        }
        sheet.addCell(new Label(0, 0, "订舱业务代理人"));
        if (book.getSupCompany() != null) {
          sheet.addCell(new Label(1, 0, book.getSupCompany().getName()));
        }
        // 设置exl表的工作标题
        String[] title = {"货物名称", "每柜毛重", "体积", "柜型", "大船公司", "成交方式", "起运港", "目的港", "船期要求", "柜型总量",
            "合作价格", "备注", "货好时间"};
        // 在Label的构造子中设计位置和内容 Lalel(col,row,"")
        Label label;
        for (int row = 1; row < book.getGoodses().size() + 2; row++) {
          if (row == 1) {
            for (int col = 0; col < title.length; col++) {
              label = new Label(col, row, title[col]);
              sheet.addCell(label);
            }
          } else if (book.getGoodses().size() > 0) {
            Goods goods = book.getGoodses().get(row - 2);
            label = new Label(0, row, goods.getName());
            sheet.addCell(label);
            jxl.write.Number number = new jxl.write.Number(1, row, goods.getGweight());
            sheet.addCell(number);
            label = new Label(2, row, goods.getVolume());
            sheet.addCell(label);
            label = new Label(3, row, goods.getCtNumType());
            sheet.addCell(label);
            if (null != book.getShipping()) {
              label = new Label(4, row, book.getShipping().getName());
              sheet.addCell(label);
            }
            label = new Label(5, row, book.getBusinessType());
            sheet.addCell(label);
            label = new Label(6, row, book.getStPort());
            sheet.addCell(label);
            label = new Label(7, row, book.getArPort());
            sheet.addCell(label);
            label = new Label(8, row, book.getShipDate());
            sheet.addCell(label);
            label = new Label(9, row, book.getCtNumType());
            sheet.addCell(label);
            label = new Label(10, row, book.getPrice());
            sheet.addCell(label);
            label = new Label(11, row, book.getRemark());
            sheet.addCell(label);
            if (null != book.getGfDate()) {
              label = new Label(12, row, book.getGfDate().toString());
              sheet.addCell(label);
            }
          }
        }
        // writableWorkbook.write();
        i++;
      }
      // 拖车的exls

      if (trial != null && trial.getGdes() != null) {
        WritableSheet sheet = writableWorkbook.createSheet("拖车", i);

        // 设置字体种类和格式
        WritableFont bold = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
        WritableCellFormat wcfFormat = new WritableCellFormat(bold);
        wcfFormat.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中

        i++;
        for (int k = 0; k < 13 + trial.getGdes().size(); k++) {
          sheet.setColumnView(k, 15);
          sheet.setRowView(k, 500);
        }
        String so = "";
        for (GoodAddress g : trial.getGdes()) {
          if ("".equals(so)) {
            so = g.getSo();
          } else {
            so = g.getSo() + "," + so;
          }
        }

        if (so != null && !"".equals(so)) {
          so = removeDuplicateSo(so);// so去重
        }

        sheet.addCell(new Label(0, 0, "货运平台拖车服务委托单", wcfFormat));
        sheet.mergeCells(0, 0, 11, 0);
        sheet.addCell(new Label(0, 1, "SO/提单号："));
        sheet.addCell(new Label(1, 1, so));
        sheet.mergeCells(1, 1, 11, 1);
        sheet.addCell(new Label(0, 2, "委托公司名称："));
        sheet.addCell(new Label(1, 2, trial.getCustomer().getName()));
        sheet.mergeCells(1, 2, 11, 2);
        sheet.addCell(new Label(0, 3, "联系人："));
        sheet.addCell(new Label(1, 3, trial.getCreator()));
        sheet.mergeCells(1, 3, 3, 3);
        sheet.addCell(new Label(4, 3, "电话 ："));
        sheet.addCell(new Label(5, 3, trial.getCustomer().getPhone()));
        sheet.mergeCells(5, 3, 7, 3);
        sheet.addCell(new Label(8, 3, "手机："));
        sheet.addCell(new Label(9, 3, trial.getCustomer().getMobile()));
        sheet.mergeCells(9, 3, 11, 3);
        sheet.addCell(new Label(0, 4, "地址："));
        sheet.addCell(new Label(1, 4, trial.getCustomer().getAddress()));
        sheet.mergeCells(1, 4, 7, 4);
        sheet.addCell(new Label(8, 4, "传真："));
        sheet.addCell(new Label(9, 4, trial.getCustomer().getFax()));
        sheet.mergeCells(9, 4, 11, 4);
        sheet.addCell(new Label(0, 5, "TO："));
        sheet.mergeCells(1, 5, 8, 1);
        sheet.addCell(new Label(1, 5, trial.getSupCompany().getName()));
        sheet.mergeCells(1, 5, 11, 5);
        sheet.addCell(new Label(0, 6, "委托内容", wcfFormat));
        sheet.mergeCells(0, 6, 11, 6);
        String[] str = {"货物名称", "SO号", "装柜工厂名称", "工厂地址", "联系人", "联系电话", "柜型", "建议装柜时间", "备注"};
        int n = 0;
        for (int k = 0; k < str.length; k++) {
          sheet.mergeCells(2, 7, 3, 7);
          sheet.mergeCells(4, 7, 5, 7);
          if (k == 3 || k == 4) {
            n++;
          }
          sheet.addCell(new Label(n, 7, str[k]));
          n++;
        }
        for (int row = 0; row < trial.getGdes().size(); row++) {
          GoodAddress g = trial.getGdes().get(row);
          sheet.mergeCells(2, row + 8, 3, row + 8);
          sheet.mergeCells(4, row + 8, 5, row + 8);
          sheet.addCell(new Label(0, row + 8, g.getName()));
          sheet.addCell(new Label(1, row + 8, g.getSo()));
          sheet.addCell(new Label(2, row + 8, g.getContacter().getCompany()));
          sheet.addCell(new Label(4, row + 8, g.getContacter().getAddress()));
          sheet.addCell(new Label(6, row + 8, g.getContacter().getName()));
          sheet.addCell(new Label(7, row + 8, g.getContacter().getPhone()));
          sheet.addCell(new Label(8, row + 8, g.getCtNumType()));
          if (g.getZhDate() != null) {
            sheet.addCell(new Label(9, row + 8,
                g.getZhDate().toString().substring(0, g.getZhDate().toString().length() - 2)));
          }
          sheet.addCell(new Label(10, row + 8, g.getRemark()));
        }
        sheet.addCell(new Label(0, trial.getGdes().size() + 8, "PI号:"));
        sheet.addCell(new Label(1, trial.getGdes().size() + 8, trial.getPi()));
        sheet.mergeCells(1, trial.getGdes().size() + 8, 3, trial.getGdes().size() + 8);

        sheet.addCell(new Label(4, trial.getGdes().size() + 8, "报关票数登记:"));
        sheet.addCell(new Label(5, trial.getGdes().size() + 8, trial.getDeclarationCount()));
        sheet.mergeCells(5, trial.getGdes().size() + 8, 6, trial.getGdes().size() + 8);

        sheet.addCell(new Label(7, trial.getGdes().size() + 8, "柜数累计:"));
        sheet.addCell(new Label(8, trial.getGdes().size() + 8, trial.getContainerTotle()));
        sheet.mergeCells(8, trial.getGdes().size() + 8, 9, trial.getGdes().size() + 8);

        // 下单时间
        String ctimeVal = trial.getCtime().toString();
        String ctime = ctimeVal.substring(0, ctimeVal.length() - 4);
        sheet.addCell(new Label(0, trial.getGdes().size() + 9, "下单日期:"));
        sheet.addCell(new Label(1, trial.getGdes().size() + 9, ctime));
        sheet.mergeCells(1, trial.getGdes().size() + 9, 3, trial.getGdes().size() + 9);
        sheet.addCell(new Label(6, trial.getGdes().size() + 9, "下单操作员:"));
        sheet.addCell(new Label(7, trial.getGdes().size() + 9, trial.getCreator()));
        sheet.mergeCells(7, trial.getGdes().size() + 9, 8, trial.getGdes().size() + 9);

        // 业务单取消理由
        sheet.addCell(new Label(0, trial.getGdes().size() + 10, "业务单取消理由"));
        sheet.addCell(new Label(1, trial.getGdes().size() + 10, cancelReason.getContent()));
        sheet.mergeCells(1, trial.getGdes().size() + 10, 11, trial.getGdes().size() + 10);

        sheet.addCell(new Label(9, trial.getGdes().size() + 11, "取消申请人:"));
        sheet.addCell(new Label(10, trial.getGdes().size() + 11, cancelReason.getCancelPerson()));
        sheet.mergeCells(10, trial.getGdes().size() + 11, 11, trial.getGdes().size() + 11);

        // 取消申请时间
        String cancelDate = "";
        if (null != cancelReason.getCancelDate()) {
          String cancelDateVal = cancelReason.getCancelDate().toString();
          cancelDate = cancelDateVal.substring(0, cancelDateVal.length() - 4);
        }

        sheet.addCell(new Label(9, trial.getGdes().size() + 12, "取消申请时间:"));
        sheet.addCell(new Label(10, trial.getGdes().size() + 12, cancelDate));
        sheet.mergeCells(10, trial.getGdes().size() + 12, 11, trial.getGdes().size() + 12);
      }
      // 报关的exls
      if (declare != null) {
        WritableSheet sheet = writableWorkbook.createSheet("报关", i);
        // 调整格子的大小
        for (int k = 0; k < 11 + declare.getCommodities().size(); k++) {
          sheet.setColumnView(k, 15);
          sheet.setRowView(k, 500);
        }
        sheet.addCell(new Label(0, 0, "报关报检业务代理人："));
        if (declare.getSupCompany() != null) {
          sheet.addCell(new Label(1, 0, declare.getSupCompany().getName()));
        }
        Label label = new Label(0, 1, "出口口岸:");
        sheet.addCell(label);
        sheet.mergeCells(1, 1, 3, 1);
        label = new Label(1, 1, declare.getExport_port());
        sheet.addCell(label);
        label = new Label(4, 1, "备案号:");
        sheet.addCell(label);
        sheet.addCell(new Label(5, 1, declare.getRecord_id()));
        sheet.addCell(new Label(6, 1, "出口日期:"));
        if (declare.getExport_date() != null) {
          sheet.addCell(new Label(7, 1, declare.getExport_date().toString()));
        }
        sheet.addCell(new Label(8, 1, "申报日期:"));

        sheet.addCell(new Label(0, 2, "经营单位:"));
        sheet.mergeCells(1, 2, 3, 2);
        sheet.addCell(new Label(1, 2, declare.getCompany_name()));
        sheet.addCell(new Label(4, 2, "运输方式:"));
        sheet.addCell(new Label(5, 2, declare.getTransport_mode()));
        sheet.addCell(new Label(6, 2, "运输工具名称:"));
        sheet.addCell(new Label(7, 2, declare.getTransport_na()));
        sheet.addCell(new Label(8, 2, "提运单号:"));
        sheet.addCell(new Label(9, 2, declare.getBl_no()));

        sheet.addCell(new Label(0, 3, "发货单位:"));
        sheet.mergeCells(1, 3, 3, 3);
        sheet.addCell(new Label(1, 3, declare.getFahuo_company_name()));
        sheet.addCell(new Label(4, 3, "贸易方式:"));
        sheet.addCell(new Label(5, 3, declare.getTrade_mode()));
        sheet.addCell(new Label(6, 3, "征免性质:"));
        sheet.addCell(new Label(7, 3, declare.getLevymode()));
        sheet.addCell(new Label(8, 3, "结汇方式:"));
        sheet.addCell(new Label(9, 3, declare.getLc_type()));

        sheet.addCell(new Label(0, 4, "许可证号:"));
        sheet.mergeCells(1, 4, 2, 4);
        sheet.addCell(new Label(1, 4, declare.getLicense_no()));
        sheet.addCell(new Label(3, 4, "运抵国(地区):"));
        sheet.addCell(new Label(4, 4, declare.getArrived_country()));
        sheet.addCell(new Label(5, 4, "指运港"));
        sheet.addCell(new Label(6, 4, declare.getArrived_port()));
        sheet.addCell(new Label(7, 4, "境内货源地:"));
        sheet.addCell(new Label(8, 4, declare.getGoods_addr()));

        sheet.addCell(new Label(0, 5, "批准文号:"));
        sheet.mergeCells(1, 5, 2, 5);
        sheet.addCell(new Label(1, 5, declare.getApproval_no()));
        sheet.addCell(new Label(3, 5, "成交方式:"));
        sheet.addCell(new Label(4, 5, declare.getDeal_mode()));
        sheet.addCell(new Label(5, 5, "运费:"));
        sheet.addCell(new Label(6, 5, declare.getFreight1()));
        sheet.addCell(new Label(7, 5, "保费:"));
        sheet.addCell(new Label(8, 5, declare.getPremium1()));
        sheet.addCell(new Label(9, 5, "杂费:"));
        sheet.addCell(new Label(10, 5, declare.getOtherfee1()));

        sheet.addCell(new Label(0, 6, "合同协议号:"));
        sheet.mergeCells(1, 6, 2, 6);
        sheet.addCell(new Label(1, 6, declare.getContract_no()));
        sheet.addCell(new Label(3, 6, "件数:"));
        sheet.addCell(new Label(4, 6, declare.getGoods_count()));
        sheet.addCell(new Label(5, 6, "包装种类:"));
        sheet.addCell(new Label(6, 6, declare.getGoods_package()));
        sheet.addCell(new Label(7, 6, "毛重(千克):"));
        sheet.addCell(new Label(8, 6, declare.getGross_weight()));
        sheet.addCell(new Label(9, 6, "净重(千克):"));
        sheet.addCell(new Label(10, 6, declare.getNet_weight()));

        sheet.addCell(new Label(0, 7, "集装箱号:"));
        sheet.mergeCells(1, 7, 2, 7);// 页面没找到暂空
        sheet.addCell(new Label(3, 7, "随附单证:"));
        sheet.mergeCells(4, 7, 8, 7);
        sheet.addCell(new Label(4, 7, declare.getSuifudan()));

        sheet.mergeCells(0, 8, 0, 9);
        sheet.addCell(new Label(0, 8, "备注:"));
        sheet.mergeCells(1, 8, 10, 9);
        sheet.addCell(new Label(1, 8, declare.getRemark()));

        // 商品订单
        String[] str = {"序号", "商品编号", "备案序号", "商品名称", "规格", "目的地", "数量", "单位", "币制", "总价", "征免"};
        for (int j = 0; j < str.length; j++) {
          sheet.addCell(new Label(j, 10, str[j]));
        }
        int j = 0;
        for (Commodity c : declare.getCommodities()) {
          sheet.addCell(new Label(0, 11 + j, j + ""));
          sheet.addCell(new Label(1, 11 + j, c.getCode_t()));
          sheet.addCell(new Label(2, 11 + j, c.getRecord_id()));
          sheet.addCell(new Label(3, 11 + j, c.getName()));
          sheet.addCell(new Label(4, 11 + j, c.getGoods_mode()));
          sheet.addCell(new Label(5, 11 + j, c.getDestination()));
          sheet.addCell(new Label(6, 11 + j, c.getCount()));
          sheet.addCell(new Label(7, 11 + j, c.getUnit()));
          sheet.addCell(new Label(8, 11 + j, c.getCurrency()));
          sheet.addCell(new Label(9, 11 + j, c.getTotal_price()));
          sheet.addCell(new Label(10, 11 + j, c.getLevymode()));
          j++;
        }
      }
      writableWorkbook.write();
      writableWorkbook.close();
      // // 文件转换为输入流
      // InputStream is = new FileInputStream(dataDir + exlFileName);
      // byte[] inByte = new byte[10244];
      // is.read(inByte);
      // this.ExlStream = new ByteArrayInputStream(inByte);
      // is.close();
      // // 删除文件
      // File file = new File(dataDir + exlFileName);
      // if(file.exists()) {
      // file.delete();
      // }
      this.ExlStream = new ByteArrayInputStream(bos.toByteArray());
      // 将输出流装换为输入流
      bos.close();
      // msg = MsgConstants.CREATEEXCEL_SUCCESS;
    } catch (Exception e) {
      // msg = MsgConstants.CREATEEXCEL_FAIL;
      e.printStackTrace();
    }
    //// TODO: 2016/8/13
    return null;
  }

  /**
   * 获取个人信息，先从联系人表读取用户id，如果不存在则在联系人表中加入个人信息，主键为用户的id
   *
   * @param shipper 发货人
   */
  @RequestMapping("/business-getSelfMsg")
  @ResponseBody
  public Result getSelfMsg(User user, Contacter shipper) {
    Result msg = null;
    // contacterBiz
    String id = user.getId();
    try {
      shipper = contacterBiz.findEntityById(id);
      if (shipper == null) {
        String sql =
            "insert into t_biz_contacter(ID, COM_ID, NAME, PHONE, MPHONE, COMPANY_NAME, ADDRESS, ZIP, FAX, EMAIL, CREATOR, CTIME, MODIFIER, MTIME) values (:id, :comId, :name, :phone, :mphone, :comName, :address, :zip,:fax, :email,:creator, sysdate, :creator, sysdate)";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("id", user.getId());
        parameters.put("comId", user.getCompany().getId());
        parameters.put("name", user.getName());
        parameters.put("phone", user.getCompany().getPhone());
        parameters.put("mphone", user.getMobile());
        parameters.put("comName", user.getCompany().getName());
        parameters.put("address", user.getCompany().getAddress());
        parameters.put("zip", "");
        parameters.put("fax", user.getCompany().getFax());
        parameters.put("email", user.getEmail());
        parameters.put("creator", user.getAccount());
        contacterBiz.excuteSql(sql, parameters);
        shipper = contacterBiz.findEntityById(id);
      }
      if (shipper == null) {
        msg = Result.newFailInstance(MsgConstants.SELF_MSG_ERROR);
      }
    } catch (Exception e) {
      e.printStackTrace();
      msg = Result.newFailInstance(MsgConstants.SELF_MSG_ERROR);
    }
    return msg;
  }

  /**
   * 根据拖车的ID查询拖车的出入闸信息
   */
  @RequestMapping("/business-queryByCn")
  public String queryByCn(CarMsg carMsg) {
    String carMsgId = HttpUtils.getParam("carMsgId");
    try {
      carMsg = carMsgBiz.findEntityById(carMsgId);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "/gtimp/business/trailOutInInfo";
  }

  /**
   * 查看毛重
   */
  @RequestMapping("/business-checkGoodGw")
  public String checkGoodGw() {
    try {
      String containerId = HttpUtils.getParam("id");
      String containerNo = HttpUtils.getParam("containerNo");
      String bizPk = containerId;
      //// TODO: 2016/8/15 service
      // SupBizServiceClient client = new SupBizServiceClient();
      // SupBaseBizQueryDTO qdto = new SupBaseBizQueryDTO();
      // String serviceUrl =
      // "http://localhost:8084/ws/supTrailBizService?wsdl";
      // String serviceUrl =
      // "http://219.130.222.62:9380/ws/supTrailBizService?wsdl";// 新港测试
      // String serviceUrl =
      // "http://192.168.0.5:8181/ws/supTrailBizService?wsdl";//
      // 新港正式112.124.20.178:8080

      String serviceUrl = "http://112.124.20.178:8080/ws/supTrailBizService?wsdl";// 新港正式
      //
      // qdto.setServiceUrl(serviceUrl);
      // qdto.setBizPk(bizPk);
      // SupTrailBizResultDTO supTrailBizResultDTO = new SupTrailBizResultDTO();
      // supTrailBizResultDTO.setContainerNo(containerNo);
      // qdto.setTrailBizResultDTO(supTrailBizResultDTO);
      // goodGw = client.checkGoodGw(qdto);
    } catch (Exception e) {
      e.printStackTrace();
    }
    //// TODO: 2016/8/15
    return null;
  }

  /**
   * 保存为常用模板
   */
  // public String saveAsModel() throws QueryException {
  // String id = HttpUtils.getParam("id");
  // try {
  // trial = trailBiz.findEntityById(id);
  // if("1".equals(trial.getCommonTemplate())) {
  // msg = MsgConstants.IS_COMMONTEMPLATE;
  // } else {
  // trial = new Trail();
  // List<String> properties = new ArrayList<String>();
  // trial.setId(id);
  // trial.setCommonTemplate("1");
  // properties.add("commonTemplate");
  // trailBiz.updateEntity(trial, properties);
  // msg = MsgConstants.SAVEMODEL_SUCCESS;
  // }
  //
  // } catch (Exception e) {
  // e.printStackTrace();
  // msg = MsgConstants.SAVEMODEL_FAIL;
  // }
  //
  // return msg;
  // }

  /**
   * set get method
   **/

  public CompanyBiz getCompanyBiz() {
    return companyBiz;
  }

  public void setCompanyBiz(CompanyBiz companyBiz) {
    this.companyBiz = companyBiz;
  }

  public String[][] getBusinessType() {
    return businessType;
  }

  public void setBusinessType(String[][] businessType) {
    this.businessType = businessType;
  }

  public String[][] getPorts() {
    return ports;
  }

  public void setPorts(String[][] ports) {
    this.ports = ports;
  }

  public String[][] getUnits() {
    return units;
  }

  public void setUnits(String[][] units) {
    this.units = units;
  }

  public String[][] getCurrencys() {
    return currencys;
  }

  public void setCurrencys(String[][] currencys) {
    this.currencys = currencys;
  }

  public String[][] getCountries() {
    return countries;
  }

  public void setCountries(String[][] countries) {
    this.countries = countries;
  }

  public String[][] getDeals() {
    return deals;
  }

  public void setDeals(String[][] deals) {
    this.deals = deals;
  }

  public String getBizState() {
    return bizState;
  }

  public void setBizState(String bizState) {
    this.bizState = bizState;
  }

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getGoodGw() {
    return goodGw;
  }

  public void setGoodGw(String goodGw) {
    this.goodGw = goodGw;
  }

  public String getClearPk() {
    return clearPk;
  }

  public void setClearPk(String clearPk) {
    this.clearPk = clearPk;
  }

  public String getModelType() {
    return modelType;
  }

  public void setModelType(String modelType) {
    this.modelType = modelType;
  }

  public String getLoadType() {
    return loadType;
  }

  public void setLoadType(String loadType) {
    this.loadType = loadType;
  }

  public String getCheckDetail() {
    return checkDetail;
  }

  public void setCheckDetail(String checkDetail) {
    this.checkDetail = checkDetail;
  }

  public String getIdentification() {
    return identification;
  }

  public void setIdentification(String identification) {
    this.identification = identification;
  }

  public String getLoadPage() {
    return loadPage;
  }

  public void setLoadPage(String loadPage) {
    this.loadPage = loadPage;
  }

  public InputStream getExlStream() {
    return ExlStream;
  }

  public String getExlFileName() {
    return exlFileName;
  }

  public File getImportExlFile() {
    return importExlFile;
  }

  public void setImportExl(File importExlFile) {
    this.importExlFile = importExlFile;
  }

  public String getImportExlFileName() {
    return importExlFileName;
  }

  public void setImportExlFileName(String importExlFileName) {
    this.importExlFileName = importExlFileName;
  }

  public String getImportExlContentType() {
    return importExlContentType;
  }

  public void setImportExlContentType(String importExlContentType) {
    this.importExlContentType = importExlContentType;
  }

  public String getDeclareStr() {
    return declareStr;
  }

  public void setDeclareStr(String declareStr) {
    this.declareStr = declareStr;
  }

  public String getIsSubmit() {
    return isSubmit;
  }

  public void setIsSubmit(String isSubmit) {
    this.isSubmit = isSubmit;
  }

  public String getBusinessId() {
    return businessId;
  }

  public void setBusinessId(String businessId) {
    this.businessId = businessId;
  }

  public String getIsRecord() {
    return isRecord;
  }

  public void setIsRecord(String isRecord) {
    this.isRecord = isRecord;
  }

  public String getCommodity_id() {
    return commodity_id;
  }

  public void setCommodity_id(String commodity_id) {
    this.commodity_id = commodity_id;
  }

  public String getGoods_number() {
    return goods_number;
  }

  public void setGoods_number(String goods_number) {
    this.goods_number = goods_number;
  }

  public String getPayMent() {
    return payMent;
  }

  public String getPayFree() {
    return payFree;
  }

  public void setPayFree(String payFree) {
    this.payFree = payFree;
  }

  public PaymentResult getPaymentResult() {
    return paymentResult;
  }

  public void setPaymentResult(PaymentResult paymentResult) {
    this.paymentResult = paymentResult;
  }

  public void setPayMent(String payMent) {
    this.payMent = payMent;
  }

  public String getMSG() {
    return MSG;
  }

  public void setMSG(String mSG) {
    MSG = mSG;
  }

  public List<String> getDeclaration_ids() {
    return declaration_ids;
  }

  public void setDeclaration_ids(List<String> declaration_ids) {
    this.declaration_ids = declaration_ids;
  }

  public List<DeclarationFree> getDeclarationFrees() {
    return declarationFrees;
  }

  public void setDeclarationFrees(List<DeclarationFree> declarationFrees) {
    this.declarationFrees = declarationFrees;
  }

  public String getCom_type() {
    return com_type;
  }

  public void setCom_type(String com_type) {
    this.com_type = com_type;
  }

  public String getSfdTempId() {
    return sfdTempId;
  }

  public void setSfdTempId(String sfdTempId) {
    this.sfdTempId = sfdTempId;
  }

}


/**
 * 加载模板的json视图
 */
class LoadModelJsonView {
  private Trail trial;
  private Declaration declare;
  private Booking book;
  private Contacter shipper;

  public Trail getTrial() {
    return trial;
  }

  public void setTrial(Trail trial) {
    this.trial = trial;
  }

  public Declaration getDeclare() {
    return declare;
  }

  public void setDeclare(Declaration declare) {
    this.declare = declare;
  }

  public Booking getBook() {
    return book;
  }

  public void setBook(Booking book) {
    this.book = book;
  }

  public Contacter getShipper() {
    return shipper;
  }

  public void setShipper(Contacter shipper) {
    this.shipper = shipper;
  }
}
